package com.woniu.job.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.job.entity.vo.ResultVO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author sunnylausong
 *
 * 2019/12/26
 * 16:32
 */
@WebFilter("/admin/*")
public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    /**
     * 管理员登录过滤
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
        // 判断url是否为登录/静态资源，是则放行
        StringBuffer url = req.getRequestURL();
        if (url.substring(url.indexOf("/admin")).equals("/admin/login")
                || url.indexOf("/admin/styles/") != -1 || url.indexOf("/admin/images/") != -1) {

            chain.doFilter(request, response);
            return;
        }
        // options 放行
        if (req.getMethod().toUpperCase().equals("OPTIONS")) {
            chain.doFilter(request, response);
            return;
        }

        // 判断管理员session存在，
        if (req.getSession().getAttribute("loginAdmin") == null) {
            // 设置跨域
            //允许跨域
            rep.setHeader("Access-Control-Allow-Origin", "http://192.168.9.222:8089");

            rep.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            rep.setHeader("Access-Control-Max-Age", "3600");
            // 这个allow-headers要配为*，这样才能允许所有的请求头
            rep.setHeader("Access-Control-Allow-Headers", "*");
            rep.setHeader("Access-Control-Allow-Credentials", "true");
            // 字符编码
            rep.setHeader("content-type", "text/json;charset=utf-8");
            rep.setCharacterEncoding("UTF-8");

            ResultVO r = ResultVO.FORBID.message("<a href='admin/login'>请登录</a>");
            ObjectMapper mapper = new ObjectMapper();
            PrintWriter writer = rep.getWriter();
            writer.write(mapper.writeValueAsString(r));

            writer.close();
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy()
    {

    }
}
